package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Override
    public ResponseResult login(AdUserDTO DTO) {
        //参数检验
        String name = DTO.getName();
        String password = DTO.getPassword();
        if(StringUtils.isBlank(name) || StringUtils.isBlank(password)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        //根据用户名查询用户信息
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if(user == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //检查用户的状态是否为9（正常）
        if(9 != user.getStatus().intValue()){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常，请联系管理员");
        }
        //对比输入的密码 和数据中的密码是否一致
        String password1 = user.getPassword();
        String salt = user.getSalt();
        String newPwd = DigestUtils.md5DigestAsHex((DTO.getPassword()+salt).getBytes());
        if(!password1.equals(newPwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名或密码错误");
        }
        //修改最近的登入时间
        user.setCreatedTime(new Date());
        //颁发token
        String token = AppJwtUtil.getToken(user.getId().longValue());

        //返回结果
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(user,userVO);
        Map map = new HashMap();
        map.put("token",token);
        map.put("user",userVO);
        return ResponseResult.okResult(map);
    }
}
